package 力扣.双指针.最长区间;

import java.util.HashMap;

public class 最多有k个不同字符的最长子字符串 {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        // write your code here
        if (s == null || s.length() == 0 || k == 0){
            return 0;
        }
        int left = -1;
        int ans = 0;
        Counter counter = new Counter();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            counter.add(c, 1);
            while (counter.size() > k){
                char t = s.charAt(++left);
                counter.add(t, -1);
                if (counter.getc(t) == 0){
                    counter.remove(t);
                }
            }
            ans = Math.max(ans, i - left);
        }
        return ans;
    }
    class Counter extends HashMap{
        public int getc(char k){
            return containsKey(k) ? (Integer) get(k) : 0;
        }
        public void add(char k ,int v){
            put(k, getc(k) + v);
        }
    }
}
